package com.ruoyi.gxdj.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/wechat")
public class WeChatLoginController extends BaseController {

    private static final String APPID = "wxa543ea34c344d4f5";
    private static final String SECRET = "b96edb8aa410fb6206b0668d7849305a";

    @Autowired
    private SysUserMapper sysUserMapper;


    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody SysUser weChatUser){
        //登录接口api
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        //设置登录接口参数
        String params = "appid="+APPID+"&secret="+SECRET+"&js_code="+weChatUser.getCode()+"&grant_type=authorization_code";
        //掉用api
        String s = HttpUtils.sendGet(url, params);
        //取openid
        JSONObject jsonObject = JSON.parseObject(s);
        Object openid = jsonObject.get("openid");
        weChatUser.setOpenId(String.valueOf(openid));
        SysUser user = sysUserMapper.selectUserByOpenId(String.valueOf(openid));
        if (StringUtils.isNull(user)){
            //新增
            sysUserMapper.insertUser(weChatUser);
        }
        SysUser user1 = sysUserMapper.selectUserByOpenId(String.valueOf(openid));
        List<SysDictData> list = sysDictDataMapper.selectDictDataByType("info_identity");
        user1.setToIdentity(user1.getIdentity()+1);
        for (SysDictData sysDictData : list) {
            if (sysDictData.getDictValue().equals(user1.getIdentity().toString())) {
                user1.setIdentityLable(sysDictData.getDictLabel());
            }
            if (sysDictData.getDictValue().equals(user1.getToIdentity().toString())){
                user1.setToIdentityLable(sysDictData.getDictLabel());
            }
        }
        return AjaxResult.success(user1);
    }
}
